// pages/order/order.js
var api = require("../../utils/api.js");
var util = require("../../utils/util.js");
//获取应用实例
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    after_type: 0, //售后类型 0正常订单 1换货订单
    lastTime: 0,
    taxpayers: true,
    modify_price: true,
    qcodeSwitch: true,
    submitCol: true,
    address:[],
    addressLength:0,
    defaultAddressId:null,
    controlDome: true, //地址弹窗
    addressSwitch: '0',
    discount: "0",
    payButton:false, //立即支付按钮可点击
    detail_img: [], //照片列表
    invoice: true,
    invoiceNeed: "0",
    invoiceType: "2",
    invoiceTextType: "1",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this;
    this.setData({
      windowHeight: app.globalData.windowHeight + 50
    })

    if (options.after_type != undefined) {
      this.setData({
        after_type: options.after_type
      })
    }

    if (options.shopId) {
      this.setData({
        shopId: options.shopId
      })
    }
    util.showLoading("加载中...");
    setTimeout(function(){
      that.cartList();
    },500)
  },
  onShow: function () {
    var that = this;
    this.setData({
      controlDome: true
    })
    //发票授权开关
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.invoiceTitle']) {
          that.setData({
            invoiceAuthorize: '1'
          })
        } else {
          that.setData({
            invoiceAuthorize: '3'
          })
        }
      }
    })
    this.addressList();
  },

  //地址列表
  addressList: function () {
    var params = new Object()
    var that = this;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'address/list',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          var addressLength = res.data.data.address_list.length;
          var addressList = res.data.data.address_list;
          for (var i = 0; i < addressList.length; i++) {
            if (addressList[i].is_default == 1) {
              var defaultAddressId = addressList[i].aid
            }
          }
          that.setData({
            defaultAddressId: defaultAddressId!=undefined?defaultAddressId:null,
            address: addressList,
            addressLength: addressLength
          })
        }
      }
    })
  },
  //添加新地址
  addAddress: function () {
    wx.navigateTo({
      url: '../addAddress/addAddress'
    })
  },
  //显示地址弹窗
  selAddress: function () {
    this.setData({
      controlDome: false
    })
  },
  //修改地址
  editorAddress: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/addAddress/addAddress?aid=' + id
    })
  },
  //删除地址
  deleteAddress: function (e) {
    var id = e.currentTarget.dataset.id;
    var that = this;

    wx.showModal({
      title: '提示',
      content: '确认删除该地址?',
      confirmColor: "#e51927",
      success: function (res) {
        if (res.confirm) {
          api.POST({
            params: {
              aid: id
            },
            url: app.globalData.base_url + 'address/del',
            success: function (res) {
              if (util.isEmpty(res.data.code)) {
                util.showStatus("删除成功")
                that.addressList();
              }
            },
            fail: function (fail) {
              util.showError("网络错误，请检查网络。");

            }
          })
        } else if (res.cancel) {
        }
      }
    })
  },

  //选择地址
  radioChange: function (e) {
    var id = e.detail.value
    var that = this;
    var list = that.data.address;
    for (var i = 0; i < list.length; i++) {
      if (list[i].aid == id) {
        var params = {
          aid: id,
          username: list[i].username,
          mobile: list[i].mobile,
          province: list[i].province.name,
          town: list[i].town.name,
          city: list[i].city.name,
          address: list[i].address,
          is_default: 1,
          street: list[i].street.name
        }
        api.POST({
          params: params,
          url: app.globalData.base_url + 'address/modify',
          success: function (res) {
            if (util.isEmpty(res.data.code)) {
              that.addressList();
              that.setData({
                controlDome: true
              })
            }
          },
          fail: function (fail) {
            util.showError("网络错误，请检查网络。");
          }
        })
      }
    }
  },

  //隐藏地址
  hiddenAddress: function () {
    this.setData({
      controlDome: true
    })
  },

  //购物车请求
  cartList: function () {
    var params = new Object()
    var that = this;
    var carNum = 0;
    var total = 0;
    params.shop_id = this.data.shopId
    // params.tokken = app.globalData.accountInfo.token
    api.POST({
      params: params,
      url: app.globalData.base_url + 'shoppingcart/goodsList',
      success: function (res) {
        util.hiddenLoading();
        if (util.isEmpty(res.data.code)) {
          if (res.data.data.hasGroup == 1) {
            that.setData({
              hasGroup: true
            })
          } else {
            that.setData({
              hasGroup: false
            })
          }

          var carts = res.data.data.list
          if (carts.length == 0) {
            carts = []
          } else {
            carts = carts[0].list;
          }
          if (carts.length > 0) {
            for (var i = 0; i < carts.length; i++) {
              var price = (that.data.after_type == 1) ? carts[i].current_price: carts[i].bottom_price;
              carts[i].total = (carts[i].num * price).toFixed(2);
              carts[i].total = (carts[i].num * price).toFixed(2);
              total += carts[i].num * (price >= 0 ? price : 0);
              carNum += carts[i].num / 1;
            }
          }
          that.setData({
            carts: carts,
            total: total.toFixed(2),
            oldTotal: total.toFixed(2)
          })
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络。");

      }
    })
  },

  //提交订单
  payOrder: function (e) {
    var that = this;
    var curTime = e.timeStamp;
    var lastTime = this.data.lastTime;
    this.setData({ lastTime: curTime })
    if ((lastTime > 0) && (curTime - lastTime < 2000)) {
      return false;//禁止连续点击
    }
    // util.showLoading("加载中");
    var params = new Object();
    params.shop_id = this.data.shopId;
    params.after_type = this.data.after_type;
    params.record = [];
    var list = [];
    for (var i = 0; i < this.data.carts.length; i++) {
      var box = {};
      box.sku_code = this.data.carts[i].sku_code
      box.num = this.data.carts[i].num
      box.price = (that.data.after_type == 1) ? this.data.carts[i].current_price : this.data.carts[i].bottom_price
      list.push(box);
    }
    params.record = JSON.stringify(list)

    if (this.data.invoiceNeed == 1) { //是否需要发票

      if (this.data.invoiceType == 2) { //电子发票
        params.invoice_email = this.data.Email;
        params.invoice_type = 2;
      } else {  //纸质发票
        params.invoice_type = 1;
        if (that.data.defaultAddressId>0){
          params.aid = that.data.defaultAddressId;
        }else{
          util.showError("请添加地址信息");
          return;
        }
      }

      if (this.data.invoiceTextType == 1) { //个人发票
        params.invoice = "个人";
      } else if (this.data.invoiceTextType == 2) { //企业发票
        params.invoice = this.data.Ename;
        params.invoice_number = this.data.Enumber;
        if (!util.isEmpty(this.data.Eaddress)) {
          params.invoice_e_r_address = this.data.Eaddress
        }

        if (!util.isEmpty(this.data.phoneNumber)) {
          params.invoice_e_tel = this.data.phoneNumber
        }

        if (!util.isEmpty(this.data.bankNumber)) {
          params.invoice_e_bank_name = this.data.bankName
          params.invoice_e_bank_number = this.data.bankNumber
        }
      }
    }
    if(that.data.after_type==1){
      var len = that.data.detail_img.length;
      if(len>0){
        for (var i = 0; i < len; i++) {
          params["exchange_img[" + i + "]"] = that.data.detail_img[i];
        }
      }else{
        util.showError("请上传换货凭证");
        return;
      }
    }
    api.POST({
      params: params,
      url: app.globalData.base_url + 'order/submit',
      success: function (res) {
        util.hiddenLoading();
        if (util.isEmpty(res.data.code)) {
          that.wxPayOrder(res.data.data.result.oid);
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络。");
      }
    })
  },

  // 订单支付
  wxPayOrder: function (oid) {
    var that = this;
    api.POST({
      params: { oid: oid },
      url: app.globalData.base_url + 'payment/getWechatInfo',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          var preData = res.data.data.payinfo;
          wx.requestPayment({
            timeStamp: preData.timeStamp,
            nonceStr: preData.nonceStr,
            package: preData.package,
            signType: preData.signType,
            paySign: preData.paySign,
            success: function (res) {
              wx.redirectTo({
                url: '../paySuccess/paySuccess?oid=' + oid,
              })
            },
            fail: function (error) {
              util.showError("支付失败");
            }
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络。");
      }
    })
  },

  //添加商品图片
  editGoodsImgEvent: function () {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed '], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        util.showLoading("加载中...");
        // console.log("本地图片：" + tempFilePaths);
        for (var i = 0; i < tempFilePaths.length; i++) {
          wx.uploadFile({
            url: app.globalData.base_url + 'img/saveImage',
            filePath: tempFilePaths[i],
            name: 'file',
            success: function (res) {
              // console.log("file:上传成功" + JSON.stringify(res));
              util.hiddenLoading();
              var data = JSON.parse(res.data);
              that.data.detail_img.push(data.data.url);
              that.setData({
                detail_img: that.data.detail_img
              })
            },
            fail: function () {
              util.hiddenLoading();
            }
          })
        }
      }
    })
  },
  deleteImg: function (e) {
    var index = e.currentTarget.dataset.index;
    var data = this.data.detail_img;
    data.splice(index, 1);
    this.setData({
      detail_img: data
    })
  },
  itemImgClick: function (e) {
    var url = e.currentTarget.dataset.url;
    var that = this;
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: that.data.detail_img // 需要预览的图片http链接列表
    })
  },

  // -------------发票-----------------------
  // 发票弹窗控制
  invoiceCol: function () {
    this.setData({
      invoice: false
    })
  },
  // 是否需要发票
  invoiceNeedCol: function (e) {
    this.setData({
      invoiceNeed: e.currentTarget.dataset.invoiceneed
    })
  },
  // 发票类型选择
  invoiceTypeCol: function (e) {
    this.setData({
      invoiceType: e.currentTarget.dataset.invoicetype
    })
  },
  // 发票抬头类型选择
  invoiceTextTypeCol: function (e) {
    this.setData({
      invoiceTextType: e.currentTarget.dataset.invoicetexttype
    })
  },
  // 企业名称输入
  EnameCol: function (e) {
    this.setData({
      Ename: e.detail.value
    })
  },
  // 纳税人识别号
  EnumberCol: function (e) {
    this.setData({
      Enumber: e.detail.value
    })
  },
  // 接收电子发票的邮箱
  EmailCol: function (e) {
    var email = e.detail.value;
    email = email.replace(/\s*/g, "");  //去除空格
    this.setData({
      Email: email
    })
  },
  // 企业注册地址
  EaddressCol: function (e) {
    this.setData({
      Eaddress: e.detail.value
    })
  },
  // 企业电话号码
  phoneNumberCol: function (e) {
    this.setData({
      phoneNumber: e.detail.value
    })
  },
  // 企业开户银行
  bankNameCol: function (e) {
    this.setData({
      bankName: e.detail.value
    })
  },
  // 企业银行账号
  bankNumberCol: function (e) {
    this.setData({
      bankNumber: e.detail.value
    })
  },
  // 个人抬头名称
  nameCol: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  // 确认发票信息
  invoiceConfirm: function () {
    var invoiceType = this.data.invoiceType;
    if (this.data.invoiceNeed == 1) { //是否需要发票
      if (invoiceType == 1) {
        this.setData({
          invoiceTypeCol: true
        })
      } else {
        this.setData({
          invoiceTypeCol: false
        })
      }
      this.invoiceTextTypeDecide();

    } else if (this.data.invoiceNeed == 0) {
      this.setData({
        invoice: true,
        invoiceTypeCol: false
      })
      return true
    }


  },
  // 个人或者企业发票判断
  invoiceTextTypeDecide: function () {
    if (this.data.invoiceTextType == 1) { //个人发票
      this.invoiceTypeDecide();
    } else if (this.data.invoiceTextType = 2) { //企业发票
      if (util.isEmpty(this.data.Ename)) {
        util.showStatus("请输入企业名称");
        return false
      }

      if (util.isEmpty(this.data.Enumber)) {
        util.showStatus("请输入纳税人识别号");
        return false
      }


      if (!util.isEmpty(this.data.phoneNumber)) {
        if (!util.validateMobile(this.data.phoneNumber)) {
          util.showStatus("企业电话号不正确");
          return false
        }
      }

      if (!util.isEmpty(this.data.bankNumber)) {
        if (util.isEmpty(this.data.bankName)) {
          util.showStatus("请输入开户行");
          return false
        }
        if (!util.checkBankNo(this.data.bankNumber)) {
          util.showStatus("银行账号不正确");
          return false
        }
      }

      this.invoiceTypeDecide();
    }
  },
  //发票类型判断
  invoiceTypeDecide: function () {
    if (this.data.invoiceType == 1) { //普通发票
      this.setData({
        invoice: true
      })
      return true
    } else if (this.data.invoiceType = 2) { //电子发票
      var email = this.data.Email;
      if (util.validateEmail(email)) {
        this.setData({
          invoice: true
        })
        return true
      } else {
        util.showStatus("邮箱地址错误");
        return false
      }
    }
  },

  //获取授权信息
  getSetting: function () {
    var that = this;
    wx.authorize({
      scope: 'scope.invoiceTitle',
      success(res) {
        that.obtainInvoice();
      },
      fail(res) {
        that.setData({
          invoiceAuthorize: '2'
        })
      }
    })
  },

  // 获取微信发票信息
  obtainInvoice: function () {
    var that = this;
    wx.chooseInvoiceTitle({
      success(res) {
        var types = res.type,
          title = res.title,
          telephone = res.telephone,
          taxNumber = res.taxNumber,
          companyAddress = res.companyAddress,
          bankName = res.bankName,
          bankAccount = res.bankAccount

        if (that.data.invoiceTextType == 2) {
          if (types == 0) {
            that.setData({
              Ename: title,
              Enumber: taxNumber,
              Eaddress: companyAddress,
              bankName: bankName,
              bankNumber: bankAccount
            })
          } else {
            util.showError("抬头类型错误");
          }

        }
      },
      fail() {
        that.setData({
          invoiceAuthorize: '2'
        })
      }
    })
  }
})